package ex0;

import ex0.expressions.ExpressionFactory;
import ex0.expressions.IExpression;
import ex0.expressions.IExpressionFactory;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * User: Roy
 * Date: 10/17/13
 */
public class Calc {

	public class State {
		public Stack<Double> valueStack = new Stack<Double>();
		public Stack<String> infixExpStack = new Stack<String>();
		boolean isError = false;
	}
	
	private State state;
    private IExpressionFactory expressionFactory;
	
	public Calc() {
		state = new State();
        expressionFactory = new ExpressionFactory(state);
	}
	
	public State process(String expression) {
		for (String tok : expression.split(" ")) {
			if (state.isError)
				return state;
			
			processToken(tok);
		}

		state.isError = state.valueStack.size() > 1 ? true : state.isError;
		return state;
	}
	
	void processToken(String token) {
        if (token.length() == 0) {
            return;
        }

        IExpression expression = expressionFactory.createExpression(token);
        if (expression == null) {
            state.isError = true;
        }
        else {
            state.valueStack.push(expression.evaluate());
            state.infixExpStack.push(expression.toStr());
        }
	}
}

